<?php

use Connection\TcpConnection;
use Events\EventInterface;
use Events\Select;

/**
 * Created by PhpStorm.
 * User: youliangzhang
 * Date: 2017/11/5
 * Time: 下午6:43
 */

class Server
{
    /**
     * 当有连接的时候触发
     * @var null
     */
    public $onConnect = null;

    protected $_socketName = null;

    public static $select = null;

    public function __construct($socketName)
    {
        $this->_socketName = $socketName;
        $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
        $fb = stream_socket_server($this->_socketName, $errno, $errstr, $flags);

        self::$select = new Select();
        self::$select->add($fb, EventInterface::EV_READ, array($this,'acceptConnection'));


    }
    /**
     * 当接收到消息的时候触发
     * @param $socket
     */
    public function acceptConnection($socket)
    {
        $new_socket = @stream_socket_accept($socket, 0, $remote_address);
        if (!$new_socket) {
            return;
        }
        // TcpConnection.
        $connection = new TcpConnection($new_socket, $remote_address);

        call_user_func($this->onConnect, $connection);
    }

    public static function run(){
        if (!self::$select) {
            throw new Exception("run fail ... ");
        }
        self::$select->loop();
    }
}